package wineshop.controller.backend;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import wineshop.domain.Manager;
import wineshop.service.ManagerService;
import wineshop.service.Impl.ManagerServiceImpl;

public class SecurityServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public SecurityServlet() {
		super();
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		request.setCharacterEncoding("utf-8");
		
		String act=request.getParameter("act").trim();
		
		//去登陆界面
		if("toLogin".equals(act)){
		   request.getRequestDispatcher("jsps/backend/login.jsp").forward(request, response);	
		} 
		else if("login".equals(act)){ //尝试登陆
			
			String loginId=request.getParameter("loginid");
			String loginPwd=request.getParameter("loginpwd");
			
			ManagerService managerService=new ManagerServiceImpl();
			Manager manager=managerService.getManagerById(loginId);
			String errMsg=null;
			
			if(manager==null)
				errMsg="没有这个用户存在,请检查!";
		    else
		    {
		    	if(!manager.getLoginPwd().equals(loginPwd))
		    		errMsg="密码不正确，请检查大小写!";
		    }
			
			if(errMsg==null){
				
				request.getSession().setAttribute("loginedMgr", manager);
				response.sendRedirect("securityMgr?act=mainscreen"); //所谓的重定向，就是帮助用户发起一个对服务器的全新的请求。
				
			}
			else
			{
				request.setAttribute("errMsg", errMsg);
				request.getRequestDispatcher("jsps/backend/login.jsp").forward(request, response);
			}
			    
			
		}
		else if("mainscreen".equals(act)){
			request.getRequestDispatcher("jsps/backend/main.jsp").forward(request, response);
		}
		else if("logout".equals(act)){
			request.getSession().removeAttribute("loginedMgr");
			request.getSession().invalidate();
			response.sendRedirect("securityMgr?act=toLogin");
		}


	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
        doGet(request,response);
	}

}
